<template>
    <div>
        <!-- <h1>userlist 用户列表</h1> -->
        <BreadCrumb name1="用户管理" name2="用户列表"></BreadCrumb>
        <el-card class="box-card">
            <el-row>
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="userParams.query" @clear="getUserList" :clearable="true">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList">
                        </el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true ">添加用户</el-button>
                </el-col>
            </el-row>
            <el-table border style="width: 100%; margin-top:10px; margin-bottom:20px" :data="userList">
                <el-table-column type="index" label="序号">

                </el-table-column>
                <el-table-column prop="username" label="用户名" width="180">
                </el-table-column>
                <el-table-column prop="role_name" label="角色名称" width="180">
                </el-table-column>
                <el-table-column prop="mobile" label="电话" width="180">
                </el-table-column>
                <el-table-column prop="email" label="邮箱">
                </el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scoped">
                        <div>
                            <el-switch v-model="scoped.row.mg_state" @change="userStateChange(scoped.row)">
                            </el-switch>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="200">
                    <template slot-scope="scoped">
                        <div>
                            <el-tooltip content="修改用户信息" placement="top-start">
                                <el-button type="primary" icon="el-icon-edit" circle @click="editShowDialog(scoped.row)">
                                </el-button>
                            </el-tooltip>

                            <el-tooltip content="删除用户" placement="top-start">
                                <el-button type="danger" icon="el-icon-delete" circle @click="deteleUserInfoById(scoped.row.id)">
                                </el-button>
                            </el-tooltip>

                            <el-tooltip content="权限分配" placement="top-start">
                                <el-button type="warning" icon="el-icon-setting" circle>
                                </el-button>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="userParams.pagenum" :page-sizes="[1, 2, 3, 4]" :page-size="userParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>

            <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addUserDialogClear">
                <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="100px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="addUserForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="addUserForm.password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addUserForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="mobile">
                        <el-input v-model="addUserForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser">添加用户</el-button>
                </span>
            </el-dialog>

            <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="30%">
                <el-form :model="editFormData" ref="editForm" label-width="100px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="editFormData.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email" :rules="addUserFormRules.email">
                        <el-input v-model="editFormData.email"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="mobile" :rules="addUserFormRules.mobile">
                        <el-input v-model="editFormData.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUserInfo">修改用户信息</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { user_list_req, users_state_req, add_user_req ,users_info_id_req,edit_users_info_req,detele_users_req} from '@/api/users.js';
import BreadCrumb from '../../../components/breadcrumb/BreadCrumb.vue';
export default {
    components: {
        BreadCrumb
    },
    created() {
        const userParamsS = JSON.parse(sessionStorage.getItem('userParams'));
        if (userParamsS) {
            this.userParams = userParamsS;
        } else {
            this.userParams = {
                query: '',
                pagenum: 1,
                pagesize: 4,
            }
        }
    },
    data() { 
        let checkEmail = (rule, value, callback) => {
            const emailReg = /^\w+@\w+(\.\w+)+$/;
            if (emailReg.test(value)) {
                return callback();
            }
            return callback(new Error('请输入合法邮箱'))
        };
        let checkMobile = (rule, value, callback) => {
            const mobileReg = /^1[3456789]\d{9}$/;
            if (mobileReg.test(value)) {
                return callback()
            }
            callback(new Error('请输入合法的手机号'))
        };
        return {
            userParams: {},
            userList: [],
            total: 0,
            addDialogVisible: false,
            addUserForm: {
                username: '',
                password: '',
                email: '',
                mobile: '',
            },
            addUserFormRules: {
                username: [
                    { required: true, message: "请输入用户名", trigger: "blur" },
                    {
                        min: 3,
                        max: 15,
                        message: "长度在 3 到 15个字符",
                        trigger: "blur",
                    },
                ],
                password: [
                    { required: true, message: "请输入用户密码", trigger: "blur" },
                        {
                            min: 5,
                            max: 15,
                            message: "长度在 5 到 15 个字符",
                            trigger: "blur",
                        },
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                        validator: checkEmail,
                        trigger: 'blur',
                    }
                ],
                mobile: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    {
                        validator: checkMobile,
                        trigger: 'blur',
                    }
                ]
            },

            editDialogVisible:false,
            editFormData:{}
        };
    },

    mounted() {

        this.getUserList();
    },

    methods: {

        async getUserList() {
            const result = await user_list_req({
                method: 'get',
                url: 'users',
                params: this.userParams,
            });
            if (result.meta.status == 200) {
                this.userList = result.data.users;
                this.total = result.data.total;
            }
        },

        handleSizeChange(newPageSize) {
            console.log(newPageSize);
            this.userParams.pagesize = newPageSize;
            sessionStorage.setItem('userParams', JSON.stringify(this.userParams));
            this.getUserList();
        },

        handleCurrentChange(newPageNum) {
            console.log(newPageNum);
            this.userParams.pagenum = newPageNum;
            sessionStorage.setItem('userParams', JSON.stringify(this.userParams));
            this.getUserList();
        },
        
        async userStateChange(newState) {
            console.log(newState);
            const result = await users_state_req({
                method: 'put',
                url: `users/${newState.id}/state/${newState.mg_state}`,
            });
            console.log(result);
            if (result.meta.status != 200) {
                newState.mg_state = !newState.mg_state;
                return this.$message.error('更新用户状态失败');
            }
            return this.$message({
                type: 'success',
                message: '更新用户状态成功',
            });
        },
        addUser(){
            this.$refs.addUserFormRef.validate(async (valid) =>{
                console.log(valid);
                if(!valid) return ;
                const result = await add_user_req({
                    method:'post',
                    url:'users',
                    data:this.addUserForm,
                });
                console.log(result);
                if(result.meta.status != 201) {
                    return this.$message.error('添加用户失败');
                }
                this.addDialogVisible = false;
                this.getUserList();
                return this.$message.success('添加用户成功');
            });
        },
        addUserDialogClear(){
            this.$refs.addUserFormRef.resetFields();
        },
        async editShowDialog(userInfo) {
            console.log(userInfo);
            const result = await users_info_id_req({
                method:'get',
                url:`users/${userInfo.id}`,
            });
            console.log(result);
            if(result.meta.status !== 200) {
                return this.$message.error('查询数据失败')
            }
            this.editFormData = result.data;
            this.editDialogVisible = true;
        },


        editUserInfo(){
            this.$refs.editForm.validate(async (valid) =>{
                if(!valid) return ;
                const result = await edit_users_info_req({
                    method:'put',
                    url:`users/${this.editFormData.id}`,
                    data:this.editFormData,
                });
                console.log(result);
                if(result.meta.status != 200) {
                    return this.$message.error('修改用户信息失败')
                }
                this.getUserList();
                this.editDialogVisible = false;
                return this.$message.success('修改用户信息成功')
            })
        },

        // deteleUserInfoById  deteleUserInfoById   deleteUserInfoById
        async deteleUserInfoById(id){
            console.log(id);
            const resultConfirm = await this.$confirm(
                '此操作将永久删除该用户，请问您是否继续',
                '提示',
                {
                    confirmButtonText:'确定',
                    cancelButtonText:'取消',
                    type:'warning',
                }
            ).catch(err=>err)
            console.log(resultConfirm);
            if(resultConfirm == 'confirm') {
                const result = await detele_users_req({
                    method:'delete',
                    url:`users/${id}`,
                });
                console.log(result);
                if(result.meta.status != 200) {
                    this.$message.error('用户删除失败')
                }
                this.$message.success('用户删除成功')
                this.getUserList();
            }
        }
    }

}
</script>

<style lang="scss" scoped>
.box-card {
    margin-top: 10px;
}
</style>